<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\controllers\CommonController;
use app\models\Order;
use app\models\OrderDetail;
use app\models\User;
use app\models\Cart;
use app\models\Product;
use app\models\Address;
use dzer\express\Express;

class OrderController extends CommonController
{
    //收银台
    public function actionCheck()
    {
        $this->layout="layout2.php";
        if(Yii::$app->session['User']['isLogin']!=1){
            return $this->redirect(['member/auth']);
        }
        $orderid= Yii::$app->request->get('orderid');
        $status= Order::find()->where('orderid=:oid',[':oid'=>$orderid])->one()->status;
        if($status != Order::CREATEORDER && $status!= Order::CHECKORSER){
            return $this->redirect(['order/index']);
        }
        $usermodel= User::find()->where('username=:name',[':name'=>Yii::$app->session['User']['username']])->one();
        $userid=$usermodel->userid;
        //1、地址信息
        $address=Address::find()->where('userid=:uid',[':uid'=>$userid])->asArray()->all();
        $addressModel=new Address();//添加购物地址
        //2、订单信息
        $orderDetail= OrderDetail::find()->where('orderid=:oid',[':oid'=>$orderid])->asArray()->all();
        $data=[];
        foreach ($orderDetail as $detail){
            $model= Product::find()->where('productid=:pid',[':pid'=>$detail['productid']])->one();
            $detail['title']=$model->title;
            $detail['cover']=$model->cover;
            $data[]=$detail;
        }
        //3、快递信息
        $express= Yii::$app->params['express'];
        $expressPrice= Yii::$app->params['expressPrice'];
        return $this->render('check',['address'=>$address,'addressModel'=>$addressModel,'orderDetail'=>$data,'express'=>$express,'expressPrice'=>$expressPrice]);
    }
    
    //用户订单
    public function actionIndex()
    {
        $this->layout="layout2.php";
        if(Yii::$app->session['User']['isLogin']!=1){
            return $this->redirect(['member/auth']);
        }
        $userid= User::find()->where('username=:uname',[':uname'=> Yii::$app->session['User']['username']])->one()->userid;
        $orders= Order::getAllOrder($userid);
        return $this->render('index',['orders'=>$orders]);
    }
    
    public function actionAdd()
    {
        if(Yii::$app->session['User']['isLogin']!=1){
            return $this->redirect(['member/auth']);
        }
        $transection= Yii::$app->db->beginTransaction();
        try{
            if(Yii::$app->request->isPost);
            $post= Yii::$app->request->post();
            $ordermodel=new Order();
            $usermodel= User::find()->where('username=:name',[':name'=> Yii::$app->session['User']['username']])->one();
            if(!$usermodel){
                throw new Exception();
            }
            $userid=$usermodel->userid;
            $ordermodel->userid=$userid;
            $ordermodel->status= Order::CREATEORDER;
            $ordermodel->createtime= time();
            if(!$ordermodel->save()){
                throw new Exception();
            }
            $orderid=$ordermodel->getPrimaryKey();
            foreach ($post['OrderDetail'] as $product){
                $model=new OrderDetail();
                $product['orderid']=$orderid;
                $product['createtime']= time();
                $data['OrderDetail']=$product;
                if(!$model->add($data)){
                    throw new Exception();
                }
                Cart::deleteAll('productid=:pid',[':pid'=>$product['productid']]);
                Product::updateAll(['num'=>$product['productnum']],'productid=:pid',[':pid'=>$product['productid']]);
            }
            $transection->commit();
        } catch (\yii\db\Exception $e){
            $transection->rollBack();
            return $this->redirect(['cart/index']);
        }
        return $this->redirect(['order/check','orderid'=>$orderid]);
    }
    
    public function actionConfirm()
    {
        //addressid,amount,status,expressid
        try{
            if(Yii::$app->session['User']['isLogin']!=1){
                return $this->redirect(['member/auth']);
            }
            if(!Yii::$app->request->isPost){
                throw new Exception();
            }
            $post= Yii::$app->request->post();
            $usermodel= User::find()->where('username=:name',[':name'=> Yii::$app->session['User']['username']])->one();
            if(empty($usermodel)){
                throw new Exception();
            }
            $userid=$usermodel->userid;
//            var_dump($post);exit;
            $ordermodel= Order::find()->where('orderid=:oid and userid=:uid',['oid'=>$post['orderid'],':uid'=>$userid])->one();
            if(empty($ordermodel)){
                throw new Exception();
            }
//            $ordermodel->scenario="update";
            $post['status']= Order::CHECKORSER;
            $details= OrderDetail::find()->where('orderid=:oid',[':oid'=> $post['orderid']])->all();
            $amount=0;
            foreach ($details as $detail){
                $amount+=$detail->productnum*$detail->price;
            }
            if($amount<=0){
                throw new Exception();
            }
            //free是免邮
            if($post['expressid']=='free'){
                $express=0;
            }else{
            $express= Yii::$app->params['expressPrice'][$post['expressid']];
            }
            if($express<=0){
                throw new Exception();
            }
            $amount+=$express;
            $post['amount']=$amount;
            $data['Order']=$post;
            if($ordermodel->load($data) && $ordermodel->save()){
                return $this->redirect(['order/pay','orderid'=>$post['orderid'],'paymethod'=>$post['paymethod']]);
            }
        } catch (\yii\db\Exception $e){
            return $this->redirect(['index/index']);
        }

    }
    
    //查询快递单号，使用组件yii2-express，在github中搜索
    public function actionGetexpress()
    {
        $expressno= Yii::$app->request->get('expressno');
        $rs = Express::search($expressno);
        echo $rs;
        exit;
    }
    
    public function actionReceived()
    {
        $orderid= Yii::$app->request->get('orderid');
        $order= Order::find()->where('orderid=:oid',[':oid'=>$orderid])->one();
        if(!empty($order) && $order->status== Order::SENDED){
            $order->status= Order::RECEIVED;
            $order->save();
        }
        return $this->redirect(['order/index']);
    }
    
}
